package com.centit.task;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.core.util.UuidUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.centit.airplanebaseinfo.po.AirplaneBaseinfo;
import com.centit.airplanebaseinfo.service.AirplaneBaseinfoManager;
import com.centit.cxtj.service.CxtjManager;
import com.centit.dtjktxlog.po.JddtDtjktxlog;
import com.centit.dtjktxlog.service.JddtDtjktxlogManager;
import com.centit.exchange.po.ExchangeRate;
import com.centit.exchange.service.ExchangeRateManager;
import com.centit.framework.components.CodeRepositoryUtil;
import com.centit.jddtgzsz.service.JddtGzszManager;
import com.centit.support.algorithm.UuidOpt;
import com.centit.util.SendEmail;

@Component
@EnableScheduling
public class DtjkTask {
	
	@Autowired
	private JddtGzszManager jddtGzszMag;

	/*@Autowired
	private AirplaneBaseinfoManager airplaneBaseinfoMag;*/
	
	@Autowired
	private CxtjManager cxtjMag;
	
	@Autowired
	private JddtDtjktxlogManager jddtDtjktxlogMag;
	
	@Autowired
	private ExchangeRateManager exchangeRateMang;
	
	@Scheduled(cron = "0 0/5 0 * * ?" )
	@Transactional
	public void djjkdata() { 
		//先查询监控规则 然后遍历
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("dataValid", "T");
		map.put("status", "1");
		JSONArray jddtGzszs = jddtGzszMag.getJSONArrayList(map,null); 
		for (int i = 0; i < jddtGzszs.size(); i++) {
			JSONObject jsonObject = jddtGzszs.getJSONObject(i);
			//根据规则名称来判断要监控什么字段
			if("飞机三证监控规则".equals(jsonObject.getString("sxname"))) {
				//获取对应的 预警期限时间
				String limitString = jsonObject.getString("txday");
				int days = Integer.valueOf(getNumeric(limitString));
				Map<String, Object> filterMap = new HashMap<String, Object>();
				filterMap.put("dataValid", "T");
				filterMap.put("status", "2");
				filterMap.put("szdqsj", days);  //dtyxDate  电台执照有效日期
				//此处 listObject方法暂时占位置 之后需要些方法 进行规定字段的日期查询 
				List<AirplaneBaseinfo> listObjects = cxtjMag.listObjects(filterMap);
				for (AirplaneBaseinfo airplaneBaseinfo : listObjects) {	
					//获取之前 已经插入过得提醒数据（未处理）
					Map<String, Object> getObjMap = new HashMap<String, Object>();
					getObjMap.put("airId", airplaneBaseinfo.getRecId());
					getObjMap.put("jksxId", jsonObject.getString("sxcode"));
					getObjMap.put("clStatus", "1");
					JddtDtjktxlog dbdtjktxlog = jddtDtjktxlogMag.getObjectByProperties(getObjMap);
					if(dbdtjktxlog != null) {
						//再次发起自动提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送三证到期短信提醒2");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机三证时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dbdtjktxlog.setZdtxTime(dbdtjktxlog.getZdtxTime()+1);//提醒完了自动提醒次数加一
						dbdtjktxlog.setZjtxDate(new Date());				//自动提醒的最后一次提醒时间
						if(airplaneBaseinfo.getDtyxDate()==null){
							continue;
						}
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getDtyxDate());
						if(syday<0) {
							dbdtjktxlog.setJcStatus("2"); 						//已到期
						}
						dbdtjktxlog.setSyday((long)syday); //剩余天数
						dbdtjktxlog.setTxType(jsonObject.getString("txtype"));
						jddtDtjktxlogMag.updateObject(dbdtjktxlog);
					} else {
						//发起提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送三证到期短信提醒");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机三证时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						JddtDtjktxlog dtjktxlog = new JddtDtjktxlog();
						dtjktxlog.setRecId(UuidOpt.getUuidAsString32());
						dtjktxlog.setAirId(airplaneBaseinfo.getRecId()); 	//飞机id
						dtjktxlog.setClStatus("1");							//未处理
						dtjktxlog.setDataValid("T");						//有效性
						dtjktxlog.setZdtxTime((long)1);						//自动提醒次数
						dtjktxlog.setZjtxDate(new Date());					//自动提醒的最后一次提醒时间
						dtjktxlog.setJksxId(jsonObject.getString("sxcode"));//检测事项id
						if(airplaneBaseinfo.getDtyxDate()==null){
							continue;
						}
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dtjktxlog.setDqDate(airplaneBaseinfo.getDtyxDate());//到期时间即为电台有效时间
						dtjktxlog.setSctxDate(new Date()); 					//首次提醒时间
						
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getDtyxDate());
						if(syday>=0) {
							dtjktxlog.setJcStatus("1"); 						//快到期
						} else {
							dtjktxlog.setJcStatus("2"); 						//已到期
						}
						dtjktxlog.setSyday((long)syday); //剩余天数
						dtjktxlog.setTxType(jsonObject.getString("txtype"));
						dtjktxlog.setInsTime(new Date());
						jddtDtjktxlogMag.saveNewObject(dtjktxlog);
					}
					
				}
				
			}
			if("飞机合同监控规则".equals(jsonObject.getString("sxname"))) {
				String limitString = jsonObject.getString("txday");
				int days = Integer.valueOf(getNumeric(limitString));
				Map<String, Object> filterMap = new HashMap<String, Object>();
				filterMap.put("dataValid", "T");
				filterMap.put("status", "2");
				filterMap.put("htdqsj", days);  //htdqsj  电台执照有效日期
				//此处 listObject方法暂时占位置 之后需要些方法 进行规定字段的日期查询 
				List<AirplaneBaseinfo> listObjects = cxtjMag.listObjects(filterMap);
				for (AirplaneBaseinfo airplaneBaseinfo : listObjects) {	
					//获取之前 已经插入过得提醒数据（未处理）
					Map<String, Object> getObjMap = new HashMap<String, Object>();
					getObjMap.put("airId", airplaneBaseinfo.getRecId());
					getObjMap.put("jksxId", jsonObject.getString("sxcode"));
					getObjMap.put("clStatus", "1");
					JddtDtjktxlog dbdtjktxlog = jddtDtjktxlogMag.getObjectByProperties(getObjMap);
					if(dbdtjktxlog != null) {
						//再次发起自动提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送合同到期短信提醒2");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机合同时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dbdtjktxlog.setAlarmR(0);
						}else{
							dbdtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dbdtjktxlog.setZdtxTime(dbdtjktxlog.getZdtxTime()+1);//提醒完了自动提醒次数加一
						dbdtjktxlog.setZjtxDate(new Date());				//自动提醒的最后一次提醒时间
						if(airplaneBaseinfo.getEndTime()==null){
							continue;
						}
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getEndTime());
						if(syday<0) {
							dbdtjktxlog.setJcStatus("2"); 						//已到期
						}
						dbdtjktxlog.setSyday((long)syday); //剩余天数
						dbdtjktxlog.setTxType(jsonObject.getString("txtype"));
						jddtDtjktxlogMag.updateObject(dbdtjktxlog);
					} else {
						//发起提醒
						if(jsonObject.getString("txtype").equals("1")) {
							//短信提醒
							System.out.println("发送合同到期短信提醒");
						}
						if(jsonObject.getString("txtype").equals("2")) {
							//邮件提醒
							try {
								SendEmail.sendEmail("您的飞机合同时间即将过期，请及时处理", "411527091@qq.com");
							} catch (Exception e) {
								System.out.println("邮件发送失败");
								e.printStackTrace();
							}
						}
						if(jsonObject.getString("txtype").equals("3")) {
							//站内消息提醒
							
						}
						//log记录
						JddtDtjktxlog dtjktxlog = new JddtDtjktxlog();
						if(jsonObject.getString("alarmR")==null||StringUtils.isBlank(jsonObject.getString("alarmR"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmR")));
						}
						if(jsonObject.getString("alarmY")==null||StringUtils.isBlank(jsonObject.getString("alarmY"))){
							dtjktxlog.setAlarmR(0);
						}else{
							dtjktxlog.setAlarmR(Integer.parseInt(jsonObject.getString("alarmY")));
						}
						dtjktxlog.setRecId(UuidOpt.getUuidAsString32());
						dtjktxlog.setAirId(airplaneBaseinfo.getRecId()); 	//飞机id
						dtjktxlog.setClStatus("1");							//未处理
						dtjktxlog.setDataValid("T");						//有效性
						dtjktxlog.setZdtxTime((long)1);						//自动提醒次数
						dtjktxlog.setZjtxDate(new Date());					//自动提醒的最后一次提醒时间
						dtjktxlog.setJksxId(jsonObject.getString("sxcode"));//检测事项id
						if(airplaneBaseinfo.getEndTime()==null){
							continue;
						}
						dtjktxlog.setDqDate(airplaneBaseinfo.getEndTime());	//到期时间即为合同到期时间
						dtjktxlog.setSctxDate(new Date()); 					//首次提醒时间
						
						int syday = differentDaysByMillisecond(new Date(),airplaneBaseinfo.getEndTime());
						if(syday>=0) {
							dtjktxlog.setJcStatus("1"); 						//快到期
						} else {
							dtjktxlog.setJcStatus("2"); 						//已到期
						}
						dtjktxlog.setSyday((long)syday); //剩余天数
						dtjktxlog.setTxType(jsonObject.getString("txtype"));
						dtjktxlog.setInsTime(new Date());
						jddtDtjktxlogMag.saveNewObject(dtjktxlog);
					}
				}
			}
		}
	}
	
	/**
	 * 过滤非数字
	 * @param str
	 * @return
	 */
	public static String getNumeric(String str) {
	    String regEx="[^0-9]";  
	    Pattern p = Pattern.compile(regEx);  
	    Matcher m = p.matcher(str);  
	    return m.replaceAll("").trim();
	}
		
	/**
	 * 求日期时间差 -天
	 * @param date1
	 * @param date2
	 * @return
	 */
	public static int differentDaysByMillisecond(Date date1,Date date2){
        int days = (int) ((date2.getTime() - date1.getTime()) / (1000*3600*24));
        return days;
    }
	
	/**
	 * ***********************************************************************************************汇率查询相关
	 */
	public static final String DEF_CHATSET = "UTF-8";
    public static final int DEF_CONN_TIMEOUT = 30000;
    public static final int DEF_READ_TIMEOUT = 30000;
    public static String userAgent =  "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";
	
    public static final String APPKEY ="c2e3787bcdc12af711198db6f6511890";
    
    static Double[] eRate = new Double[10];
	
    
    /**
     * 	每天0：01分调用接口存储本天的汇率
     */
    @Scheduled(cron = "00 00 08 * * ?" )
	@Transactional
    public void getHl() {
    	String result1 =null;
        String url ="http://web.juhe.cn:8080/finance/exchange/rmbquot";//请求接口地址
        Map<String,String> params = new HashMap<String,String>();//请求参数
        params.put("key",APPKEY);//APP Key
        params.put("type","");//两种格式(0或者1,默认为0)	
        try {
			result1 =net(url, params, "GET");
			//将字符串转化成JSON对象
            JSONObject object = JSONObject.parseObject(result1);
            //转化成JSON数组
            JSONArray resultList = object.getJSONArray("result");
            for (int i = 0; i < resultList.size(); i++) {
            	JSONObject json = resultList.getJSONObject(i);
            	JSONObject jsonObject = json.getJSONObject("data1");
            	ExchangeRate exchangeRate = new ExchangeRate();
            	exchangeRate.setFbDate(jsonObject.getString("date"));
            	exchangeRate.setForeignBuyPri(jsonObject.getString("fBuyPri"));
            	exchangeRate.setMoneyBuyPri(jsonObject.getString("mBuyPri"));
            	exchangeRate.setForeignSellPri(jsonObject.getString("fSellPri"));
            	exchangeRate.setMoneySellPri(jsonObject.getString("mSellPri"));
            	exchangeRate.setBankConversionPri(jsonObject.getString("bankConversionPri"));
            	exchangeRateMang.saveNewObject(exchangeRate);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
    
    /**
    *
    * @param strUrl 请求地址
    * @param params 请求参数
    * @param method 请求方法
    * @return  网络请求字符串
    * @throws Exception
    */
   public static String net(String strUrl, Map params,String method) throws Exception {
       HttpURLConnection conn = null;
       BufferedReader reader = null;
       String rs = null;
       try {
           StringBuffer sb = new StringBuffer();
           if(method==null || method.equals("GET")){
               strUrl = strUrl+"?"+urlencode(params);
           }
           URL url = new URL(strUrl);
           conn = (HttpURLConnection) url.openConnection();
           if(method==null || method.equals("GET")){
               conn.setRequestMethod("GET");
           }else{
               conn.setRequestMethod("POST");
               conn.setDoOutput(true);
           }
           conn.setRequestProperty("User-agent", userAgent);
           conn.setUseCaches(false);
           conn.setConnectTimeout(DEF_CONN_TIMEOUT);
           conn.setReadTimeout(DEF_READ_TIMEOUT);
           conn.setInstanceFollowRedirects(false);
           conn.connect();
           if (params!= null && method.equals("POST")) {
               try (DataOutputStream out = new DataOutputStream(conn.getOutputStream())) {
                   out.writeBytes(urlencode(params));
               }
           }
           InputStream is = conn.getInputStream();
           reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
           String strRead = null;
           while ((strRead = reader.readLine()) != null) {
               sb.append(strRead);
           }
           rs = sb.toString();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           if (reader != null) {
               reader.close();
           }
           if (conn != null) {
               conn.disconnect();
           }
       }
       return rs;
   }
   
   public static String urlencode(Map<String,Object>data) {
       StringBuilder sb = new StringBuilder();
       for (Map.Entry i : data.entrySet()) {
           try {
               sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue()+"","UTF-8")).append("&");
           } catch (UnsupportedEncodingException e) {
               e.printStackTrace();
           }
       }
       return sb.toString();
   }

}
